import socket
import time
import logging
from datetime import datetime

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler("logs/wits_a_sender.log"),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger(__name__)


class WITSASender:
    def __init__(self, host, port, data_file="examples.txt"):
        self.host = host
        self.port = port
        self.data_file = data_file
        self.socket = None
        self.connected = False
        self.records = []

        # 加载样例数据
        self.load_records_from_file()

    def load_records_from_file(self):
        """从文件加载WITS-A记录"""
        try:
            with open(self.data_file, 'r', encoding='utf-8') as file:
                content = file.read()

            # 按记录分割（每个记录以&&开头，以!!结尾）
            raw_records = content.split('&&')[1:]  # 跳过第一个空元素

            for raw_record in raw_records:
                if '!!' in raw_record:
                    # 提取记录内容（从开头到!!之前）
                    record_content = raw_record.split('!!')[0].strip()
                    if record_content:
                        # 重建完整的WITS-A记录格式，字段间用\r\n分隔
                        # 先分割各个字段行
                        lines = record_content.split('\n')
                        # 重建记录，字段间用\r\n分隔
                        reconstructed_record = '&&\r\n' + '\r\n'.join(
                            line.strip() for line in lines if line.strip()) + '\r\n!!\r\n'
                        self.records.append(reconstructed_record)
                        logger.info(f"加载记录，包含 {len(lines)} 个字段")

            logger.info(f"成功加载 {len(self.records)} 条WITS-A记录")

        except Exception as e:
            logger.error(f"加载数据文件失败: {e}")

    def connect(self):
        """连接到WITS-A服务器"""
        try:
            self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.socket.connect((self.host, self.port))
            self.connected = True
            logger.info(f"成功连接到WITS-A服务器 {self.host}:{self.port}")
            return True
        except Exception as e:
            logger.error(f"连接失败: {e}")
            return False

    def send_data(self):
        """向服务器发送数据"""
        if not self.connected:
            logger.error("未连接到服务器")
            return False

        if not self.records:
            logger.error("没有可发送的记录")
            return False

        try:
            logger.info("开始向服务器发送WITS-A数据...")
            record_count = 0

            for record in self.records:
                if not self.connected:
                    break

                try:
                    # 发送记录
                    self.socket.send(record.encode('ascii'))
                    record_count += 1

                    # 记录前几行用于日志显示
                    lines = record.split('\r\n')
                    preview = ' | '.join(lines[:3]) + ('...' if len(lines) > 3 else '')
                    logger.info(f"发送记录 {record_count}/{len(self.records)}: {preview}")

                    # 每条记录间隔3秒
                    time.sleep(3)

                except Exception as e:
                    logger.error(f"发送记录失败: {e}")
                    break

            logger.info(f"数据发送完成，共发送 {record_count} 条记录")

        except Exception as e:
            logger.error(f"与服务器通信时出错: {e}")
            return False

        return True

    def disconnect(self):
        """断开连接"""
        if self.socket:
            self.socket.close()
        self.connected = False
        logger.info("已断开与WITS-A服务器的连接")


def main():
    # 配置WITS-A服务器信息
    HOST = "127.0.0.1"  # WITS-A服务器IP地址
    PORT = 5001  # WITS-A服务器端口
    DATA_FILE = "samples_20250927_01.txt"  # 数据文件路径

    # 创建发送器实例
    sender = WITSASender(HOST, PORT, DATA_FILE)

    try:
        # 连接到服务器
        if sender.connect():
            # 开始发送数据
            sender.send_data()
    except KeyboardInterrupt:
        logger.info("用户中断程序")
    except Exception as e:
        logger.error(f"程序运行出错: {e}")
    finally:
        sender.disconnect()


if __name__ == "__main__":
    main()